import json

from flask import Flask, render_template, request, redirect, jsonify

from db import UserDB, PoemsDB, DescDB

user_db = UserDB()
poems_db = PoemsDB()
desc_db = DescDB()
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
user_form = {}


@app.route('/admin')
def admin():
    if user_form.get('username') and user_form.get('password'):
        return render_template('主页面.html')
    else:
        return redirect('/login')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        global user_form
        username = request.form.get('username')
        password = request.form.get('password')

        result = user_db.search(username)
        if result == password.encode():
            user_form['username'] = username
            user_form['password'] = password
            return redirect('/admin')
        else:
            return render_template('登录-弹窗.html')
    return render_template('登录.html')


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        if user_db.search(username):
            return render_template('注册-弹窗.html')
        else:
            user_db.add(username, password)
            return redirect('/login')
    return render_template('注册.html')


@app.route('/')
def index():
    return redirect('/login')


@app.route('/write_poem', methods=['GET', 'POST'])
def write_poem():
    if user_form:
        if request.method == 'POST':
            data = {
                'title': request.form.get('title'),
                'author': request.form.get('author') if request.form.get('author') else user_form.get('username'),
                'content': request.form.get('content').split('\r\n')
            }
            poems_db.insert(data)
            return redirect('/admin')
        return render_template('写诗.html')
    else:
        return redirect('/login')


@app.route('/view_personal_information')
def view_personal_information():
    username = user_form.get('username')
    if username:
        result = desc_db.find(username)
        if result:
            return render_template('查看个人信息.html', data=result)
        else:
            return render_template('查看个人信息-未绑定.html')
    else:
        return redirect('/login')

@app.route('/edit_personal_information', methods=['GET', 'POST'])
def edit_personal_information():
    if user_form.get('username'):
        if request.method == 'POST':
            d = request.form.copy()
            d2 = {}
            # print(d
            if user_form.get('password') == d.get('password'):
                hobby = []
                for k, v in d.items():
                    if 'like_' in k:
                        like_one = k.replace('like_read', '阅读').replace('like_write', '写作').replace('like_dai', '发呆')
                        hobby.append(like_one)
                    else:
                        d2[k] = v
                d2['hobby'] = hobby
                desc_db.insert(username=user_form.get('username'), data=d2)
                return redirect('/admin')
        return render_template('修改个人信息.html')
    else:
        return redirect('/login')

@app.route('/poem')
def poem():
    name = request.args.get('name')
    result = poems_db.search(name)
    # print(result)
    return render_template('古诗显示.html', **result)

@app.route('/delete')
def delete():
    name = request.args.get('name')
    return str(poems_db.delete(name))

@app.route('/poems')
def poems():
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=10)
    start = (page - 1) * limit
    all_data = poems_db.all()
    data = [start:start + limit]
    result = dict(code=0, msg='', count=len(all_data), data=data)
    return jsonify(result)


if __name__ == '__main__':
    app.run()
